package club.zbiao.modules.system.service.query;

import club.zbiao.modules.system.domain.Role;
import club.zbiao.modules.system.repo.RoleRepository;
import club.zbiao.modules.system.service.dto.RoleDTO;
import club.zbiao.modules.system.service.mapper.RoleMapper;
import club.zbiao.modules.system.service.spec.RoleSpec;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jie
 * @date 2018-12-03
 */
@Service
@CacheConfig(cacheNames = "role")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleQueryService extends BaseQueryServiceImpl<RoleDTO, Role, RoleMapper,RoleSpec, RoleRepository> {


    @Cacheable(key = "'findByUsers_Id:' + #p0")
    public List<Role> findByUsers_Id(Long id) {
        return queryRepo.findByUsers_Id(id).stream().collect(Collectors.toList());
    }

    @Cacheable(keyGenerator = "keyGenerator")
    public Integer findByRoles(Set<Role> roles) {
        Set<RoleDTO> roleDTOS = new HashSet<>();
        for (Role role : roles) {
            roleDTOS.add(findById(role.getId()));
        }
        return Collections.min(roleDTOS.stream().map(RoleDTO::getLevel).collect(Collectors.toList()));
    }

    class Spec implements Specification<Role> {

        private String name;

        public Spec(String name) {
            this.name = name;
        }

        @Override
        public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {

            List<Predicate> list = new ArrayList<Predicate>();

            if (!ObjectUtils.isEmpty(name)) {
                /**
                 * 模糊
                 */
                list.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        }
    }
}
